package com.deimos.dataBase.utils;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.deimos.dataBase.Scenario;

/**
 * Servlet implementation class BuildDBServlet
 */
public class GetScenarioServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetScenarioServlet() {
	super();
	// TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		PrintWriter out = null;
		out = response.getWriter();

		String queryString = request.getQueryString();
		StringBuffer scenarioId = new StringBuffer();
		
		parseRequest(queryString, scenarioId);
		out.println(Scenario.getScenario(scenarioId.toString()));
	}

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	// TODO Auto-generated method stub
    }

    private boolean parseRequest(String request, StringBuffer scenarioId) {
	try {
	    if (request.toLowerCase().contains("scenario")) {
		String[] parameters = request.split("&");
		if (parameters.length < 1) return false;
		for (String parameter : parameters) {
		    String[] atribute = parameter.split("=");
		    if (atribute.length != 2) return false;
		    if (atribute[0].toLowerCase().compareTo("scenario") == 0)
			scenarioId.append(atribute[1]);
		}
	    } else return false;
	} catch (Exception e) {
	    return false;
	}
	
	return true;
    }

}
